<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/16
 * Time: 9:36
 */

namespace Hrm\Controllers;

use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\hrm\XhhrmApprove;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmExperience;
use Admin\Models\hrm\XhhrmInterview;
use Admin\Models\hrm\XhhrmResource;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\hrm\XhhrmStaffAccessory;
use Admin\Models\hrm\XhhrmStaffContact;
use Admin\Models\sys\XhsysConfig;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\XhException;
use Hrm\Models\XHHrmAttendence;
use Hrm\Models\XHHrmSalary;
use Modules\Power;
use Phalcon\Mvc\Dispatcher;
use Services\HundredMail;

class StaffInfoController extends ControllerBase
{

    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        if (in_array(strtolower($dispatcher->getActionName()), [
            strtolower('index'),
            strtolower('getStaff'),
        ])) {
            return true;
        }
        //检查是否已登陆，否则跳转到登陆页面
        if (!User::isLogin()) {
            Main::goLoginPage();
            return false;
        }
        return true;
    }

    public static $enums = [
        'iEmploySource' => [1 => '网站投递', 2 => '猎头推荐', 3 => '招聘会', 4 => '内部员工推荐'],
        'bMarried' => [1 => '已', 0 => '未'],
        'iWorkStatus' => [
            1 => '兼职',
            2 => '实习',
            3 => '全职',
            4 => '应届',

        ],
        'iStaffStatus' => [
            1 => '在职',
            2 => '离职',
            3 => '退休',
        ],
        'iOfferStatus' => [
            1 => '试用',
            2 => '正式',
            3 => '非正式',
            4 => '其他'
        ],
        'iUserSex' => ['1' => '男', 2 => '女'],
        'mSuggest' => ['复试', '条件尚可但暂不考虑,可纳入后备人才库', '不予以考虑', '试用', '变更岗位试用'],
//        'iRegisterType' => [1 => '本地城镇', 2 => '本地农村', 3 => '外地城镇', 4 => '外地农村' ],
        'iRegisterType' => [
            10 => '本地城镇（主城区）',
            11 => '外地城镇（省内市外）',
            12 => '外地城镇（省外）',
            20 => '本地农村（主城区）',
            21 => '外地农村（省内市外）',
            22 => '外地农村（省外）',
        ],

    ];

    private static $accessoryConfig = [
        'identity'  => '身份证',
        'register'  => '户口簿或户籍证明',
        'graduate'  => '最高学历毕业证书',
        'degree'    => '学位证书',
        'profession'=> '职称证书',
        'residence' => '暂住证(非本地户籍)',
        'health'    => '体检表(杭州三级以上(含)医院体检证明)',
        'contract'  => '解除(终止)劳动合作证明(无工作者免)',
        'icon'      => '头像'
    ];

    /**
     * 职工信息
     *
     * create by dale  20181018
     */
    public function indexAction()
    {
        $staffCode = $this->request->getQuery('staffCode', 'string');
        if ($staffCode) {
            $staffId = $this->unlockText($staffCode);
            $staff = XhhrmStaff::findFirst($staffId);
        } else { //另一种途径进入
            if (User::isLogin()) {
                if (User::isAdmin()) {
                    $staffId = 535;
                    $staff = XhhrmStaff::findFirst($staffId);
                } else {
                    $userId = Main::getLoginUserInfo('userId');
                    $staff = XhhrmStaff::findFirst([
                        'conditions' => 'bDelete= 0 and iUserId = :iUserId:',
                        'bind'       => ['iUserId' => $userId],
                    ]);
                }
            } else {
                Main::goLoginPage();
            }
        }
        if (!$staff) {
            return $this->sendViewError('未找到职工信息');
        }
        $this->view->pick('staff_info/index.volt');
        Assets::importJs('js/staff_info/index.js');
//        return $this->view->setVars([
//            ''
//        ]);
    }

    /**
     * 加密
     *
     * @param $txt
     * @param string $key
     *
     * @return string
     *
     * create by dale  20181018
     */
    private function lockText($txt, $key = 'xh_staff')
    {
        $txt = $txt . $key;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $nh = rand(0, 64);
        $ch = $chars[$nh];
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = base64_encode($txt);
        $tmp = '';
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64;
            $tmp .= $chars[$j];
        }
        return urlencode(base64_encode($ch . $tmp));
    }

    /**
     * 解密
     *
     * @param $txt
     * @param string $key
     *
     * @return string
     *
     * create by dale  20181018
     */
    private function unlockText($txt, $key = 'xh_staff')
    {
        $txt = base64_decode(urldecode($txt));
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $ch = $txt[0];
        $nh = strpos($chars, $ch);
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = substr($txt, 1);
        $tmp = '';
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) {
                $j += 64;
            }
            $tmp .= $chars[$j];
        }
            return trim(base64_decode($tmp), $key);
    }

    /**
     * 员工tab
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20181016
     */
    public function staffTabAction()
    {
        $this->view->pick('staff_info/staffTab');
        Assets::importJs('js/staff_info/staffTab.js');
        $staffId = $this->request->getQuery('staffId', 'int');
        if ($staffId) {
            $info = XhhrmStaff::findFirst($staffId)->toArray();
            if ($info) {
                $this->view->setVar('info', $info);
            }
        }
        return $this->view->setVars([
            'enums' => self::$enums,
            'staffArr' => Hrm::getFlowStaffWithDepName()
        ]);
    }

    /**
     * 保存员工
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20181016
     */
    public function saveStaffAction()
    {
        $id = $this->request->getPost('iStaffId', 'int');
        $postData = $this->request->getPost();
//        $depId = $this->request->getPost('depId', 'int');
        try {
            $this->db->begin();
            if (!$id) {
                return $this->sendErrorResponse(500, '编辑接口，不支持新增');
            }
            XhhrmStaff::modifyStaff($postData);
//            if ($id) {
//                $obj = XhhrmStaff::findFirst($id);
//            } else {
//                $obj = new XhhrmStaff();
//            }
//            $obj->assign($postData);
//            if ($depId) {
//                $depArr = XhhrmDepart::getDepIdArr($depId);
//                $sDepIds = ','.implode(',', $depArr).',';
//                $obj->sDepIds = $sDepIds;
//            }
//            if ($obj->sHundredMail) {
//                try {
//                     $check = HundredMail::checkMail($obj->sHundredMail);
//                     if (!$check) {
//                         HundredMail::addMail($obj->sHundredMail, $obj->sStaffName, $obj->sSelfPhone, 'xuehai123456');
//                     }
//                } catch (\Exception $e) {
//                    $this->createCommitLog($e->getMessage(),$e instanceof XhException ? $e->getDescription() : $e->getTrace());
//                }
//            }
//            if (!$obj->save()) {
//                return $this->sendErrorResponse(500, 'staff姓名保存失败');
//            }
//            if ($obj->iUserId) {
//                $user = XhsysUser::findFirst([
//                    'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
//                    'bind'       => ['iUserId' => $obj->iUserId]
//                ]);
//                if ($user) {
//                    if ($user->sUserName != $obj->sStaffName) {
//                        $user->sUserName = $obj->sStaffName;
//                        if (!$user->save()) {
//                            throw new XhException('user姓名保存失败');
//                        }
//                    }
//                    if ($user->sSelfPhone != $obj->sSelfPhone) {
//                        $user->sSelfPhone = $obj->sSelfPhone;
//                        if (!$user->save()) {
//                            throw new XhException('user电话保存失败');
//                        }
//                    }
//                }
//
//            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 职工信息
     *
     * @param null $tag
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20181016
     */
    public function experienceAction($tag = null)
    {
        try {
            $staffId = $this->request->getQuery('staffId', 'int');
            if (!$staffId) {
                $this->sendViewError('未传入职工id');
            }
            $expArr = XhhrmExperience::find([
                'conditions' => 'bDelete = 0 and sTag = :sTag: and iStaffId = :iStaffId:',
                'bind' => ['sTag' => $tag, 'iStaffId' => $staffId ],
                'order' => 'sStartTime desc'
            ])->toArray();
            $this->view->pick('staff_info/experience');
            Assets::layUI();
            Assets::importJs('js/staff_info/experience.js');
            return $this->view->setVars([
                'staffId' => $staffId,
                'tag' => $tag,
                'infoArr' => $expArr
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 经历列表
     *
     * @param null $tag
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20181016
     */
    public function expFormAction($tag = null)
    {
        $this->view->pick('staff_info/expForm');
        Assets::importJs('js/staff_info/expForm.js');
        $id = $this->request->getQuery('id');
        if ($id) {
            $info = XhhrmExperience::findFirst($id)->toArray();
            if ($info) {
                $this->view->setVar('info', $info);
            }
        }
        return $this->view->setVars([
            'tag' => $tag,
            'staffId' => $this->request->getQuery('staffId', 'int')
        ]);
    }

    /**
     * 保存经历
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181016
     */
    public function saveExperienceAction()
    {
        try {
            $this->db->begin();
            $iSEId = $this->request->getPost('iSEId', 'int');
            if ($iSEId) {
                $obj = XhhrmExperience::findFirst($iSEId);
            } else {
                $obj = new XhhrmExperience();
            }
            $obj->assign($this->request->getPost());
            if ($obj->iStaffId) {
                $staff = XhhrmStaff::findFirst([
                    'columns' => 'iSourceId',
                    'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
                    'bind'       => ['iStaffId' => $obj->iStaffId]
                ]);
                if ($staff->iSourceId && !$obj->iSourceId) {
                    $obj->iSourceId = $staff->iSourceId;
                }
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            if ($obj->sTag == 'contract') { //合同签订
                $expArr = XhhrmExperience::find([
                    'conditions' => 'bDelete = 0 and sTag = :sTag: and iStaffId = :iStaffId:',
                    'bind'       => ['sTag' => 'contract', 'iStaffId' => $obj->iStaffId],
                    'order'      => 'sStartTime desc',
                ])->toArray();
                if ($expArr) {
                    $nowContract = Tool::getValue($expArr, 0, null);
                    if ($nowContract) {
                        $staff = XhhrmStaff::findFirst($obj->iStaffId);
                        if (!$staff) {
                            throw new \Exception('未找到该员工id');
                        }
                        $staff->sContractStatus = $nowContract['sMajor'];
                        $staff->sContentDate    = $nowContract['sStartTime'].'-'.$nowContract['sEndTime'];
                        $staff->iSignNumber     = count($expArr);
                        if (!$staff->save()) {
                            throw new XhException('教师更新失败');
                        }
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 删除个人经历
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181016
     */
    public function delExperienceAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmExperience::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(500, '为找到该记录');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 家庭
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20181016
     */
    public function familyAction()
    {
        $staffId = $this->request->getQuery('staffId', 'int');
        if (!$staffId) {
            $this->sendViewError('未传入人才id');
        }
        $this->view->pick('staff_info/family');
        Assets::importJs('js/staff_info/family.js');
        $contact = XhhrmStaffContact::find([
            'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
            'bind'       => ['iStaffId' =>  $staffId]
        ])->toArray();
        if ($contact) {
            $this->view->setVar('familyArr', $contact);
        }
        return $this->view->setVars([
            'staffId' => $staffId
        ]);
    }

    /**
     * 家庭表单
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20181016
     */
    public function familyFormAction()
    {
        $staffId = $this->request->getQuery('staffId', 'int');
        $this->view->pick('staff_info/familyForm');
        Assets::importJs('js/staff_info/familyForm.js');
        $iSCId = $this->request->getQuery('iSCId', 'int');
        if ($iSCId) {
            $info = XhhrmStaffContact::findFirst($iSCId)->toArray();
            $this->view->setVar('info', $info);
        }
        return $this->view->setVars([
            'staffId' => $staffId
        ]);
    }

    /**
     * 保存家庭
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181016
     */
    public function saveFamilyAction()
    {
        try {
            $id = $this->request->getPost('iSCId', 'int');
            $postData = $this->request->getPost();
            if ($id) {
                $obj = XhhrmStaffContact::findFirst($id);
            } else {
                $obj = new XhhrmStaffContact();
            }
            $obj->assign($postData);
            if ($obj->iStaffId) {
                $staff = XhhrmStaff::findFirst([
                    'columns' => 'iSourceId',
                    'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
                    'bind'       => ['iStaffId' => $obj->iStaffId]
                ]);
                if ($staff->iSourceId && !$obj->iSourceId) {
                    $obj->iSourceId = $staff->iSourceId;
                }
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 删除家庭
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181016
     */
    public function delFamilyAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmStaffContact::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(500, '为找到该记录');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 保存
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181016
     */
    public function employAction()
    {
        $staffId = $this->request->getQuery('staffId', 'int');
        if (!$staffId) {
            return $this->sendViewError('缺少参数');
        }
        $this->view->pick('staff_info/employ');
        Assets::select2();
        Assets::layUI();
        Assets::importJs('js/staff_info/employ.js');
        if ($staffId) {
            $info = XhhrmStaff::findFirst($staffId)->toArray();
            if ($info['sDepIds']) {
                $depIdArr = array_values(array_filter(explode(',', $info['sDepIds'])));
                $depId = Tool::getValue($depIdArr, 0, null);
                if ($depId) {
                    $info['depId'] = $depId;
                }
            }
            $this->view->setVar('info', $info);
        }
        return $this->view->setVars([
            'staffId' => $staffId,
            'registerType' => self::$enums['iRegisterType'],
            'depArr' => XhhrmDepart::getDepEnum(),
            'iStaffLevel' => XhsysEnum::getEnumByNodeName('职位等级'),
            'iWorkStatus' => self::$enums['iWorkStatus'],
            'iStaffStatus' => self::$enums['iStaffStatus'],
            'iOfferStatus' => self::$enums['iOfferStatus'],
        ]);
    }


    /**
     * 附件表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     *
     * create by dale  20181016
     */
    public function accessoryAction()
    {
        try {
            $staffId = $this->request->getQuery('staffId');
            if (!$staffId) {
                return $this->sendViewError('缺少参数staffId');
            }
            $this->view->pick('staff_info/accessory');
            Assets::importJs('../customer/js/myMain.js');
            Assets::viewer();
            Assets::importJs('js/staff_info/accessory.js');
            $accessoryArr = XhhrmStaffAccessory::find([
                'conditions' => 'bDelete = 0 and iStaffId = :staffId:',
                'bind'       => ['staffId' => $staffId]
            ])->toArray();
            if ($accessoryArr) {
                $accessoryArr = array_column($accessoryArr, null, 'sType');
                foreach ($accessoryArr as &$accessory) {
                    if ($accessory['mUrls']) {
                        if (is_string($accessory['mUrls'])) {
                            $accessory['mUrls'] = explode(',', $accessory['mUrls']);
                        }
                    }
                }
            }
            return $this->view->setVars([
                'staffId'      => $staffId,
                'accessoryArr' => $accessoryArr,
                'accessoryConfig' => self::$accessoryConfig
            ]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 保存附件
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181016
     */
    public function saveAccessoryAction()
    {
        try {
            $file = Tool::getValue($this->request->getUploadedFiles(), 0);
            $fileName = $file->getName();
            $sType = $this->request->getPost('sType', 'string');
            $iStaffId = $this->request->getPost('iStaffId', 'int');
            if (!$fileName) {
                return  $this->sendErrorResponse(500, '没有文件上传');
            }
            if (!in_array(strtolower($file->getExtension()), ['bmp', 'jpg', 'png', 'jpeg'])) {
                return $this->sendErrorResponse(500, '格式不支持');
            }
            $fullPath = TEMP_PATH . $fileName;
            if (!is_writable(TEMP_PATH)) {
                return $this->sendErrorResponse(500, TEMP_PATH . '缓存无写入权限');
            }
            $file->moveTo($fullPath);
            $url = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
            if (!$url) {
                return $this->sendErrorResponse(500, '上传到文件服务器失败');
            }
            @unlink($fullPath);
            $obj = XhhrmStaffAccessory::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId: and sType = :sType:',
                'bind'       => ['sType' => $sType, 'iStaffId' => $iStaffId]
            ]);
            if (!$obj) {
                $obj = new XhhrmStaffAccessory();
            }
            $obj->sType    = $sType;
            $obj->iStaffId = $iStaffId;
            if ($obj->mUrls) {
                $urlArr = array_values(array_filter(explode(',', $obj->mUrls)));
                if ($urlArr) {
                    $urlArr[] = $url;
                    $urlArr = array_values(array_filter(array_unique($urlArr)));
                    $obj->mUrls = implode(',', $urlArr);
                }
            } else {
                $obj->mUrls = $url;
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 删除附件图片
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181017
     */
    public function delAccessoryAction()
    {
        try {
            $id  = $this->request->getPost('id', 'int');
            $url = $this->request->getPost('url', 'string');
            if (!$id || !$url) {
                return $this->sendErrorResponse(500, '缺少参数');
            }
            $obj = XhhrmStaffAccessory::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(500, '附件对象未找到');
            }
            if ($obj->mUrls) {
                $urlArr = is_string($obj->mUrls) ? explode(',', $obj->mUrls) : $obj->mUrls;
                if (!is_array($urlArr)) {
                    return $this->sendErrorResponse(500, '存储格式不正确');
                }
                if ($urlArr) {
                    foreach ($urlArr as $index => $imgUrl) {
                        if ($imgUrl == $url) {
                            unset($urlArr[$index]);
                        }
                    }
                    $urlArr = array_values($urlArr);
                    if ($urlArr) {
                        $obj->mUrls = implode(',', $urlArr);
                    } else {
                        $obj->mUrls = '';
                    }
                    if (!$obj->save()) {
                        return $this->sendErrorResponse(500, '保存失败');
                    }
                }
                return $this->sendSuccessResponse('保存成功');
            } else {
                return $this->sendErrorResponse(500, '没有图片不需要删除');
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

//    /**
//     * 创建百分邮箱
//     *
//     * create by dale  20181017
//     */
//    public function createHundredMailAction()
//    {
//        try {
//            $phone = $this->request->get('phone', 'string');
//            $checkExist = HundredMail::checkMail($phone . '@100fen.cn');
//            if (!$checkExist) {
//                return $this->sendErrorResponse(500, '邮箱已创建');
//            } else {
//                $res = HundredMail::addMailByPhone($phone,'','xuehai123456');
//                if ($res) {
//                    return $this->sendSuccessResponse('邮箱创建成功');
//                } else {
//                    return $this->sendErrorResponse('邮箱创建失败');
//                }
//            }
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

//    /**
//     * 新建邮箱
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by dale  20181130
//     */
//    public function addHundredMailAction()
//    {
//        try {
//            $phone = $this->request->get('phone', 'string');
//            $res = HundredMail::addMailByPhone($phone, '', 'xuehai123456');
//            if ($res) {
//                return $this->sendSuccessResponse('邮箱创建成功');
//            } else {
//                return $this->sendErrorResponse('邮箱创建失败');
//            }
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

//    /**
//     * 获取邮箱一个用户信息
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by dale  20181128
//     */
//    public function getMailUserAction()
//    {
//        $uid = $this->request->getQuery('uid');
//        try {
//            $data = HundredMail::getUserInfo($uid);
//            return $this->sendJsonResponse($data);
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

//    /**
//     * 改变邮箱密码
//     *
//     * @return bool|mixed|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by dale  20181129
//     */
//    public function changeMailPasswordAction()
//    {
//        $uid = $this->request->getQuery('uid');
//        $password = $this->request->getQuery('password');
//        if (!$uid ||  !$password) {
//            return $this->sendErrorResponse(400, '缺少参数');
//        }
//        try {
//            $data = HundredMail::modifyMailPassword($uid, $password);
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

    /**
     * 百分邮箱
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181130
     */
    public function hundredMailListAction()
    {
        try {
            Assets::easyUI();
            Assets::importJs('js/staff_info/hundredMailList.js');
            $this->view->setTemplateBefore('listForm');
//            $this->view->pick('mine/hundredMailList');
            Template::exists('Info_Email', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
            $listButtonArr = $formButtonArr = $listSearchArr = array();
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
                'icon' => 'fa-search', 'style' => 'margin-left:10px');
            if (Power::exist('Hrm_Staff_Edit')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_modifyPassword', 'text' => '修改密码', 'icon' => 'fa-pencil');
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_emptyMail', 'text' => '清除邮箱', 'icon' => 'fa-pencil');
            }
            return $this->view->setVars([
                'List' => Template::createList('list', 'Info_Email', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                ]),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 获取邮箱信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181130
     */
    public function getHundredMailAction()
    {
        try {
            $key = $this->request->getPost('key', 'string');
            $sql = "select * from (select count(sHundredMail) as num, sHundredMail from XHHrm_Staff GROUP BY sHundredMail) as a where a.num > 1 ";
            $repeatedMail = $this->db->fetchAll($sql);
            if ($repeatedMail) {
                $repeatedMail = array_column($repeatedMail, 'sHundredMail');
            }
            $builder = $this->modelsManager->createBuilder()
                ->columns(['s.iStaffId', 's.sStaffName', 's.sDepIds','s.sSelfPhone','s.sHundredMail'])
                ->from(['s' => 'Admin\Models\hrm\XhhrmStaff'])
                ->where("s.bDelete=0 and sHundredMail is not null and sHundredMail <> ''");
            if ($key) {
                $builder->andWhere(
                    's.sHundredMail like :key: or s.sStaffName like :key: or s.sSelfPhone like :key:',
                    ['key' => '%'.$key.'%']
                );
            }
            $mailInfoArr = [];
            try {
                $mailData = HundredMail::getUserList();
                if ($mailData !== false) {
                    foreach ($mailData as $row) {
                        $mailInfoArr[$row['@attributes']['name']] = $row['status'];
                    }
                }
            } catch (XhException $e) {
                $this->createCommitLog('获取邮箱信息失败', $e->getDescription());
            } finally {
                $data = Main::runBuilderPage($builder);
                foreach ($data['rows'] as &$row) {
                    if ($row['sDepIds']) {
                        $row['sDepIds'] = XhhrmDepart::getDepName($row['sDepIds']);
                    }
                    if ($mailInfoArr) {
                        $mail = Tool::getValue($mailInfoArr, $row['sHundredMail'], '');
                        if ($mail) {
                            $row['createStatus'] = '已创建';
                            $row['openStatus'] = $mail;
                        } else {
                            $row['createStatus'] = '未创建';
                            $row['openStatus'] = '';
                        }
                    }
                    if ($repeatedMail && in_array($row['sHundredMail'], $repeatedMail)) {
                        $row['sHundredMail'] = "<div style=\"color: red\">{$row['sHundredMail']}</div>";
                    } else {
                        $row['sHundredMail'] = "<div>{$row['sHundredMail']}</div>";
                    }
                }
                unset($row);
                return $this->sendJsonResponse($data);
            }

        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 修改邮箱密码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181130
     */
    public function modifyMailPasswordAction()
    {
        try {
            if (!Power::exist('Hrm_Staff_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $uid = $this->request->getPost('uid', 'string');
            $password = $this->request->getPost('password', 'string');
            if (!$uid || !$password) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $res = HundredMail::modifyMailPassword($uid, $password);
            if (!$res) {
                return $this->sendErrorResponse(500, '修改失败');
            }
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 清除邮箱
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181130
     */
    public function emptyEmailAction()
    {
        try {
            $this->db->begin();
            if (!Power::exist('Hrm_Staff_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $staffIds = $this->request->getPost('staffIds', 'string');
            if (!$staffIds) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            if (!is_array($staffIds)) {
                return $this->sendErrorResponse(500, '参数不匹配');
            }
            $staffObjArr = XhhrmStaff::find([
                'conditions' => 'bDelete = 0 and iStaffId in ({ids:array})',
                'bind'       => ['ids' => $staffIds]
            ]);
            foreach ($staffObjArr as $staffObj) {
                $staffObj->sHundredMail = '';
                if (!$staffObj->save()) {
                    throw new XhException('保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('清除成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 获取邮箱信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181130
     */
    public function getMailInfoAction()
    {
        try {
            if (!Power::exist('Hrm_Staff_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $uid = $this->request->getPost('uid', 'string');
            if (!$uid) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $mailInfo = HundredMail::getUserInfo($uid);
            $mailInfo['loginName'] = $mailInfo['login_name'];
//            $mailInfo = [
//                "status" => "\n\tSuccess\n\t",
//                "description" => "\n\tGet userinfo Success\n\t",
//                "loginName" => "13957583763@100fen.cn",
//                "password" => "xu9vrYhCq3EhQ",
//                "realname" => "13957583763"
//            ];
            return $this->sendJsonResponse($mailInfo);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 获取部门枚举
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181205
     */
    public function ajaxGetFlowDepAction()
    {
        try {
            $depArr = XhhrmDepart::getDepEnum();
            return $this->sendJsonResponse($depArr);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 导出职工工号模板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181205
     */
    public function exportStaffForNumberAction()
    {
        $this->view->disable();
        if (!Power::exist('Hrm_Staff')) {
            return $this->sendErrorResponse(403, '缺少权限');
        }
        $depIds = $this->request->getQuery('depIds', 'string');
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns('iStaffId,sStaffName,sDepIds,tCreateDate')
                ->from('Admin\Models\hrm\XhhrmStaff')
                ->where('bDelete = 0 and iStaffStatus = 1')
                ->orderBy('tCreateDate asc');
            if ($depIds) {
                $depIds = explode(',', $depIds);
                $str = [];
                foreach ($depIds as $depId) {
                    $str[] = " sDepIds like  '%,{$depId},%' ";
                }
                $str = implode(' or ', $str);
                $builder->andWhere($str);
            }
            $data = $builder->getQuery()->execute()->toArray();
            foreach ($data as &$row) {
                $row['sDepIds'] = XhhrmDepart::getDepName($row['sDepIds']);
                $row['sStaffNumber'] = '';
            }
            unset($row);
            $title = [
                'iStaffId'     => '职工id(请勿编辑)',
                'sStaffName'   => '职工姓名',
                'sDepIds'      => '所属部门',
                'tCreateDate'  => '创建时间',
                'sStaffNumber' => '工号'
            ];
            $dataSource = [];
            foreach ($data as $key => $examine) {
                $row = [];
                foreach ($title as $filed => $name) {
                    $row[$filed] = Tool::getValue($examine, $filed);
                }
                $dataSource[] = $row;
            }
            Tool::exportExcelOnline('工号模板', $title, $dataSource);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 导入职工工号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181210
     */
    public function importStaffNumberAction()
    {
        try {
            $file = $this->request->getUploadedFiles()[0];
            $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
            $filePath = TEMP_PATH . '/' . $fileName;
            $file->moveTo($filePath);
            $dataSource = Tool::readExcel($filePath, true);
            $indexTitleArr = @$dataSource['title'];
            $convertTitleArr = [
                'sStaffName'   => '姓名',
                'sStaffNumber' => '工号'
            ];
            $convertTitleArr = array_flip($convertTitleArr); //键值对反转
            $filedIndexArr = []; //字段和index对应关系数组
            foreach ($indexTitleArr as $index => $title) {
                $field = Tool::getValue($convertTitleArr, $title, null);
                if ($field) {
                    $filedIndexArr[$field] = $index;
                }
            }

            $data  = @$dataSource['data'];
            $errorArr = [];
            $total = count($data);
            $error = 0;
            $skip = 0;
            $success = 0;
            foreach ($data as $index => $row) {
                $conditionArr = [];
                foreach ($filedIndexArr as $filed => $number) {
                    $conditionArr[$filed] = $row[$number];
                }
                $staffNumber = XhhrmStaff::count([
                    'conditions' => 'bDelete = 0 and iStaffStatus = 1 and sStaffName = :sStaffName:',
                    'bind'       => ['sStaffName' => $conditionArr['sStaffName']],
                ]);
                if ($staffNumber != 1) {
                    $errorArr[] = $conditionArr;
                    $error++;
                    continue;
                }
                $obj = XhhrmStaff::findFirst([
                    'conditions' => 'bDelete = 0 and iStaffStatus = 1 and sStaffName = :sStaffName:',
                    'bind'       => ['sStaffName' => $conditionArr['sStaffName']],
                ]);
                if ($obj->sStaffNumber == $conditionArr['sStaffNumber']) {
                    $skip++;
                    continue;
                }
                if (!$obj->sStaffNumber) {
                    $obj->sStaffNumber = $conditionArr['sStaffNumber'];
                    if (!$obj->save(null, null, false)) {
                        $errorArr[] = $conditionArr;
                        $error++;
                        continue;
                    }
                }
                $success++;
            }
            return $this->sendJsonResponse(
                [
                'code' => 200,
                'data' => $errorArr,
                'msg'  => "共执行{$total}次，成功{$success}次，失败{$error}次，跳过{$skip}次。"
                ]
            );
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 新增工号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181211
     */
    public function addStaffNumberAction()
    {
        try {
            $staffNumber = $this->request->getPost('staffNumber', 'string');
            $staffId = $this->request->getPost('staffId', 'string');
            if (!$staffId || !$staffNumber) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmStaff::findFirst($staffId);
            if (!$obj) {
                return $this->sendErrorResponse(500, '未找到该id对应的职工');
            }
            if ($obj->sStaffNumber) {
                return $this->sendErrorResponse(500, '该职工工号已经存在');
            }
            $staffNumber = trim(strtoupper($staffNumber));
            if (strlen($staffNumber) != 7) {
                return $this->sendErrorResponse(500, '工号的长度不为七位');
            }
            $check = XhhrmStaff::findFirst([
                'conditions' => 'bDelete = 0 and sStaffNumber =:sStaffNumber:',
                'bind' => ['sStaffNumber' => $staffNumber]
            ]);
            if ($check) {
                return $this->sendErrorResponse(500, '工号已经存在');
            }
            $obj->sStaffNumber = $staffNumber;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('添加工号成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 导入在职工信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181218
     */
    public function importStaffAction()
    {
        $this->view->disable();
        try {
            $file = $this->request->getUploadedFiles()[0];
            $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
            $filePath = TEMP_PATH . '/' . $fileName;
            $file->moveTo($filePath);
            $arr = XhhrmStaff::importStaff($filePath);
            @unlink($filePath); //删除
            return $this->sendJsonResponse(
                [
                    'code' => 200,
                    'data' => $arr['errorArr'],
                    'msg'  => "共执行{$arr['totalNum']}次，成功{$arr['successNum']}次，失败{$arr['errorNum']}次。"
                ],
                true
            );
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 导入离职职工信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190221
     */
    public function importLeaveStaffAction()
    {
        $this->view->disable();
        try {
            $file = $this->request->getUploadedFiles()[0];
            $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
            $filePath = TEMP_PATH . '/' . $fileName;
            $file->moveTo($filePath);
            $arr = XhhrmStaff::importLeaveStaff($filePath);
            @unlink($filePath); //删除
            return $this->sendJsonResponse(
                [
                    'code' => 200,
                    'data' => $arr['errorArr'],
                    'msg'  => "共执行{$arr['totalNum']}次，成功{$arr['successNum']}次，失败{$arr['errorNum']}次。"
                ],
                true
            );
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 新增职工(特殊)
     *
     * @return string
     *
     * create by dale  20190221
     */
    public function addStaffFormAction()
    {
        if (!Power::exist('Hrm_Staff_Add')) {
            return $this->sendViewError('缺少权限');
        }
        try {
            $type = $this->request->getQuery('type', 'string');
            if ($type) {
                $this->view->setVar('type', $type);
            }
            $this->view->pick('staff_info/addStaff');
            Assets::importJs('js/staff_info/addStaff.js');
            return $this->view->setVars([
                'enums' => self::$enums
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 保存职工信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190221
     */
    public function addStaffByTypeAction()
    {
        $type = $this->request->getPost('type', 'string');
        $postData = $this->request->getPost();
        if (!$type) {
            return $this->sendErrorResponse(400, '缺少保存类型');
        }
        if (!Power::exist('Hrm_Staff_Add')) {
            return $this->sendErrorResponse(403, '缺少权限');
        }
        try {
            if ($type == 'office') {
                if (!$postData['sStaffName'] || !$postData['sIdentityCode']) {
                    return $this->sendErrorResponse(400, '缺少必要参数');
                }
                if ($postData['iStaffId']) {
                    return $this->sendErrorResponse(500, '该接口不支持修改');
                }
                if (!XhhrmStaff::checkIdentityCode($postData['sIdentityCode'])) {
                    return $this->sendErrorResponse(500, '该身份号码已经存在');
                };
                XhhrmStaff::addStaff($postData);
            } elseif ($type == 'leave') {
                $obj = new XhhrmStaff();
                if (!$postData['sStaffName']) {
                    throw new \Exception('职工姓名必填');
                }
                $obj->assign($postData);
                $obj->sCreateMode = 'staff_save';
                $obj->iStaffStatus = 2;
                if (!$obj->save()) {
                    throw new \Exception('离职职工信息新增失败');
                }
            } elseif ($type == 'special') {
                $obj = new XhhrmStaff();
                if (!$postData['sStaffName']) {
                    throw new \Exception('职工姓名必填');
                }
                $obj->assign($postData);
                $obj->sCreateMode = 'staff_save';
                $obj->bSpecial = 1;
                $obj->iStaffStatus = 1;
                if (!$obj->save()) {
                    throw new \Exception('离职职工信息新增失败');
                }
            } else {
                return $this->sendErrorResponse(500, '未知type类型');
            }

            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }



    /**
     * 改变职工的工作状态
     *
     * created by dale 2017/8/26
     */
    public function changeStatusAction()
    {
        $ids = $this->request->getPost('ids', 'string');
        $status = $this->request->getPost('status', 'string');
        $type = $this->request->getPost('type', 'string');
        $date = $this->request->getPost('date', 'string');
        $reason = $this->request->getPost('sLeaveReason', 'string');
//        var_dump($reason);die;
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        }
        if (!is_array($ids) || !$status ||!$type) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            if ($type == 'bSpecial') {
                $status -=1;
            }
            XhhrmStaff::changeStaffStatus($ids, $type, $status, $date, $reason);
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 编辑特殊职工信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190221
     */
    public function modifySpecialStaffAction()
    {
        if (!Power::exist('Hrm_Staff_Edit')) {
            return $this->sendErrorResponse(403, '没有编辑权限');
        }
        $postData = $this->request->getPost();
        if (!$postData['iStaffId']) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            $obj = XhhrmStaff::findFirst($postData['iStaffId']);
            if (!$obj) {
                return $this->sendErrorResponse(400, '未找到记录');
            }
            $obj->assign($postData);
            if (!$obj->save()) {
                throw new \Exception('保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }



//    public function testAction()
//    {
//        $file = $this->request->getUploadedFiles()[0];
//        $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
//        $filePath = TEMP_PATH . '/' . $fileName;
//        $file->moveTo($filePath);
////        $data = Tool::getExcelFieldDataByTitle(
////            $filePath,
////            [
////                '设备号' => 'code',
////                '账号' =>   'account'
////            ]
////            , 0);
//        @unlink($filePath); //删除
//    }




}